import Vue from 'vue'
import VueRouter from 'vue-router'

import MyLogin from '@/views/login'
import MyLayout from '@/views/layout'
import MyHome from '@/views/home'
import MyAsk from '@/views/ask'
import MyVideo from '@/views/video'
import MyMine from '@/views/mine'
import MineEdit from '@/views/mine/userEdit'
import Detail from '@/views/article'
import Search from '@/views/search'
import SearchRes from '@/views/search/SearchRes'
import MyChat from '@/views/mine/MyChat'

// 导入store
import store from '@/store'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  { path: '', redirect: '/home' },
  { name: 'login', path: '/login', component: MyLogin },
  { name: 'edit', path: '/mine/edit', component: MineEdit },
  { name: 'detail', path: '/detail/:id', component: Detail },
  { name: 'search', path: '/search', component: Search },
  { name: 'results', path: '/search/results', component: SearchRes },
  { name: 'chat', path: '/mine/chat', component: MyChat },
  {
    name: 'layout',
    path: '/layout',
    component: MyLayout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: MyHome,
        meta: { needKeep: true }
      },
      { name: 'ask', path: '/ask', component: MyAsk },
      { name: 'video', path: '/video', component: MyVideo },
      {
        name: 'mine',
        path: '/mine',
        component: MyMine,
        meta: {
          // 路由元信息，代表把一些数据存到路由对象上
          // 或者换句话说相当于给这个打标记
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫
// to：   去哪（路由对象）
// from： 从哪来（路由对象）
// next： 是一个函数，调用它代表放行，不调用就是不放行
router.beforeEach((to, from, next) => {
  // 判断要去的(to)是不是需要登录的页面
  if (to.meta.needLogin) {
    // 代表是需要登录的页面
    // 判断有没有token
    if (store.state.user.tokenObj.token) {
      // 登录了，直接放行
      next()
    } else {
      // 没登录，打回登录页
      Toast('请先登录')
      // 原本想去哪就记录去哪的路径
      next({ name: 'login', query: { back: to.path } })
    }
  } else {
    // 不需要登录的页面，直接放行
    next()
  }
})

// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

export default router
